package com.hjh.pro2.util;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.StringWriter;
import java.util.Properties;

public class VelocityUtils {
    private VelocityUtils() {
        init();
    }

    private static class VelocityUtilsHandler{
        private static  VelocityUtils  instance = new VelocityUtils();
    }

    public static VelocityUtils getInstance(){
        return VelocityUtilsHandler.instance;
    }


    public   void init() {
        Properties p = new Properties();
        p.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(p);
    }

    public   Template getTemplate(String template) {
        return Velocity.getTemplate(template, "UTF-8");
    }


    /**
     * 组合模版，然后把内容复制到新的文件中
     * @param template
     * @param ctx
     * @param filePath
     */
    public   String write2File(String template,VelocityContext ctx,String filePath){
        Template tpl = getTemplate(template);

        StringWriter sw = new StringWriter();
        tpl.merge(ctx, sw);

        String content = sw.toString();
        FileUtils.write2File(filePath,content);

        return content;

    }


}
